﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;

using System.Web.Mvc;
using Think.Lenovo.Com.Models;
using Think.Lenovo.Com.Models.Users;
using Think.Lenovo.Com.DataAccess;
using Think.Lenovo.Com.DataAccess.User;
using Think.Lenovo.Com.Common;
namespace Think.Lenovo.Com.Controllers.Filter
{
    public class PowerFilterAttribute:ActionFilterAttribute,IRequiresSessionState
    {
        public String PowerCode { set; get; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Object user = HttpContext.Current.Session["User"];

            if (user != null)
            {
                bool havePower = false;
                #region//在此用户的权限列表中查找指定的权限
                LinkedList<PowerModel> powers = (LinkedList<PowerModel>)HttpContext.Current.Session["UserPowers"];
                foreach (PowerModel p in powers)
                {
                    if (p.Code == this.PowerCode)
                    {
                        havePower = true;
                        break;
                    }
                }
                #endregion

                if (havePower)
                {
                    return;
                }
                else 
                {
                    ViewResult vr = new ViewResult();
                    vr.ViewName = "/Views/ViewNoPower.cshtml";
                    filterContext.Result = vr;
                }
            }
            else
            {
                 ViewResult vr = new ViewResult();
                 vr.ViewName ="/Views/ViewLogin.cshtml";
                 filterContext.Result = vr;
            }
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            #region//在这里,如果Action发生异常,记录日志
            if (filterContext.Exception != null)
            {
                String logRoot = System.Configuration.ConfigurationManager.AppSettings["LogRoot"];
                if(String.IsNullOrEmpty(logRoot))
                {
                    logRoot = "./";
                }
                Log.RecordLog(logRoot, filterContext.Exception);
                ViewResult vr = new ViewResult();
                vr.ViewName = "/Views/ViewError.cshtml";
                filterContext.Result = vr;
            }
            #endregion
        }  
    }
}
